<script setup lang="ts">
import type { PageQuery } from '#/api/common';

import { computed, onMounted, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { $t } from '@vben/locales';

import { useDebounceFn } from '@vueuse/core';

import { useVbenForm } from '#/adapter/form';
import { getProductList } from '#/api/iot/product';
import {
  addSubscribe,
  subscribeDetail,
  updateSubscribe,
} from '#/api/iot/relay/serverSubscribe';
import { getDictOptions } from '#/utils/dict';

const emit = defineEmits<{ reload: [] }>();
const isUpdate = ref(false);

const [BasicModal, modalApi] = useVbenModal({
  onClosed: handleClosed,
  onConfirm: handleSubmit,
  onOpenChange: handleOpenChange,
});

const [BasicForm, formApi] = useVbenForm({
  schema: [
    {
      component: 'Select',
      fieldName: 'productId',
      label: '产品名称',
      rules: 'required',
    },
    {
      component: 'Select',
      componentProps: {
        mode: 'multiple',
        optionFilterProp: 'label',
        options: getDictOptions(DictEnum.IOT_MESSAGE_TYPE),
        allowClear: true,
      },
      fieldName: 'messageType',
      label: '推送消息类型',
      rules: 'selectRequired',
    },
  ],
  showDefaultActions: false,
  commonConfig: {
    formItemClass: 'col-span-2',
    componentProps: {
      class: 'w-full',
    },
  },
});

function setupForm(update: boolean) {
  formApi.updateSchema([
    {
      componentProps: {
        disabled: update,
      },
      fieldName: 'productId',
    },
  ]);
}

const title = computed(() => {
  return isUpdate.value ? $t('pages.common.edit') : $t('pages.common.add');
});
async function handleOpenChange(open: boolean) {
  if (!open) {
    return;
  }
  modalApi.modalLoading(true);
  const { id, update } = modalApi.getData();
  isUpdate.value = update;
  setupForm(update);
  if (id && update) {
    const res = await subscribeDetail(id);
    const formValues = {
      ...res,
      messageType: res.messageType.split(','), // 变成数组
    };
    formApi.setValues(formValues);
  }
  modalApi.modalLoading(false);
}

async function handleSubmit() {
  try {
    modalApi.modalLoading(true);
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    const data = await formApi.getValues();
    data.messageType = data.messageType.join(',');
    const { id, update } = modalApi.getData();
    data.id = id;
    await (update ? updateSubscribe(data) : addSubscribe(data));
    emit('reload');
    handleClosed();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.modalLoading(false);
  }
}

async function handleClosed() {
  modalApi.close();
  await formApi.resetForm();
}

const initFormData = async (val?: string) => {
  const params: PageQuery = {};
  if (val) {
    params.productName = val;
  }
  const res = await getProductList(params);
  const options = res.rows || [];

  // 产品信息
  formApi.updateSchema([
    {
      componentProps: {
        fieldNames: { label: 'productName', value: 'id' },
        options,
        showSearch: true,
        filterOption: false,
        onSearch: useDebounceFn(async (val: string) => {
          initFormData(val);
        }, 300),
      },
      fieldName: 'productId',
    },
  ]);
};

onMounted(() => {
  initFormData();
});
</script>

<template>
  <BasicModal
    :close-on-click-modal="false"
    :fullscreen-button="false"
    :title="title"
  >
    <div class="flex flex-col gap-[12px]">
      <BasicForm />
    </div>
  </BasicModal>
</template>
